$(() => {
    // 这个数组用来存放用户列表数据
    var userAry = []

    const renderAddUserForm = () => {
        $('#userbox').html(template('useraddTpl'))
    }
    renderAddUserForm()
    // 渲染用户列表
    const renderUserList = () => {
        $('#userlist').html(template('userlistTpl', {
            data: userAry
        }))
    }

    $('#userbox').on('submit', '#addusers', function () {
        var formdata = $(this).serialize();
        // console.log(formdata);
        $.ajax({
            type: 'post',
            url: '/users',
            data: formdata,
            success: (res) => {
                location.reload();
            },
            error: () => {
                $('#err').show()
                $('#error').html('用户添加失败')
            }
        })
        return false;
    }) //添加用户功能

    $('#userbox').on('change', '#avatar', function () {
        var avatarData = new FormData();
        // console.log(this.files[0]);
        avatarData.append('avatar', this.files[0]);

        $.ajax({
            type: 'post',
            url: '/upload',
            data: avatarData,
            processData: false,
            contentType: false,
            success: (res) => {
                $('#preview').attr('src', res[0].avatar)
                $('#hiddenAvatar').val(res[0].avatar)
            },
            error: () => {
                console.log('添加失败');
            }
        })

    }) //头像上传功能

    $(function () {
        // console.log(555);
        $.ajax({
            type: 'get',
            url: '/users',
            success: (res) => {
                userAry.push(...res)
                // console.log(userAry)
                renderUserList()
                $('#addusers')[0].reset()
            }
        })
    }) //用户列表功能模块

    $('#userlist').on('click', '.del', function () {
        var isConfirm = confirm('您真的要删除吗?');
        var id = $(this).attr('data-id');
        if (isConfirm) {
            $.ajax({
                url: '/users/' + id,
                type: 'delete',
                success: function () {
                    userAry = userAry.filter(v => v._id !== id)

                    renderUserList()
                }
            })
        }
    }) //用户删除模块

    $('#userlist').on('click', '.edit', function () {
        var id = $(this).attr('data-id');
        const user = userAry.find(v => v._id === id)
        // console.log(user);
        $('#userbox').html(template('usereditTpl', user))
    })

    $('#userbox').on('submit', '#edtusers', function () {
        const data = $(this).serialize()
        var id = $('#editbtn').attr('data-id');
        // console.log(data, id);
        $.ajax({
            url: '/users/' + id,
            type: 'PUT',
            data: data,
            success: (newres) => {
                const oldUser = userAry.find(v => v._id === newres._id)
                Object.assign(oldUser, newres)

                renderUserList()
                renderAddUserForm()

            }
        })
        return false
    })
    //用户编辑模块


    //用户批量删除模块
    $('#chescks').on('change', () => { //点击全选时
        const checked = $('#chescks').prop('checked') //获取选中的状态
        // console.log(checked);

        $('#userlist :checkbox').prop('checked', checked) //通过全选按钮的状态确定列表的按钮是否被选择
        $('#dels').attr('disabled', !checked)
    })

    $('#userlist').on('change', ':checkbox', () => {
        const checkedLen = $('#userlist :checkbox:checked').length
        // console.log(checkedLen);
        $('#chescks').prop('checked', checkedLen == userAry.length)
        $('#dels').attr('disabled', checkedLen == 0)
    })

    $('#dels').on('click', function () {
        if ($(this).attr('disabled') !== undefined) return //当在禁用时停止向下执行
        const delArr = []
        $('#userlist :checkbox:checked').each((i, v) => {
            delArr.push(v.dataset.id)
        }) //循环遍历选中的用户 将用户iD存放到delArr数组中

        // console.log(delArr);
        let isConfirm = confirm('您真的要删除以下用户吗?');
        if (isConfirm) {
            $.ajax({
                url: `/users/${delArr.join('-')} `, //拼接url
                type: 'delete',
                success: () => {
                    userAry = userAry.filter(v => !delArr.includes(v._id)) //过滤掉被删除了的用户从数组中删除
                    renderUserList() //重新渲染列表数据
                }
            })
        }
    })
})